<template>
  <view class="publishWrap">
    <uv-form
      ref="uvFormRef"
      :model="pushData"
      :rules="rules"
      errorType="message"
    >
      <view class="topSelect">
        <uv-gap height="20rpx"></uv-gap>
        <PublishTabs v-model="pushData" />
        <uv-gap v-if="!isExchangeType" height="40rpx"></uv-gap>
        <uv-gap v-else height="20rpx"></uv-gap>
        <SellType v-if="!isExchangeType" v-model="pushData" />
      </view>
      <uv-gap height="20rpx"></uv-gap>
      <PublishUploadImg v-model="pushData" />
      <uv-gap height="20rpx"></uv-gap>
      <PublishInput v-model="pushData" />
      <uv-gap height="50rpx"></uv-gap>
    </uv-form>

    <view class="pulishButton">
      <uv-button
        type="primary"
        shape="circle"
        :loading="submitLoading"
        color="linear-gradient(to right, rgba(89, 195, 248, 1), rgba(54, 161, 238, 1))"
        text="发布"
        @click="handlerPublish"
      ></uv-button>
    </view>

    <uv-gap height="50rpx"></uv-gap>
  </view>
</template>

<script setup>
import { onMounted, ref, watch, provide } from "vue";
import { onLoad, onUnload, onReady } from "@dcloudio/uni-app";
import PublishTabs from "/components/PublishTabs/index.vue";
import SellType from "/components/PublishRadio/SellType.vue";
import PublishUploadImg from "/components/PublishUploadImg/index.vue";
import PublishInput from "/components/PublishInput/index.vue";

import useBackAlert from "../../utils/backAlert.js";
import usePublishType from "/components/PublishTabs/config.js";

import articleManagement from "/api/articleManagement.js";

// 返回是否弹出询问
const isBackAlert = ref(false);
const { showBackAlert, hideBackAlert } =
  useBackAlert("内容尚未发布，退出后无法保存内容！");

const pushData = ref({
  articleType: 1,
  merchantCategory: "0", // 0：珊瑚，1：海水鱼，2：设备，3：其他
  title: "", // 标题
  content: "", // 描述
  images: "", // 图片地址
  price: "", // 价格
  location: "", // 发帖城市，格式：省,市,区
  locationId: "", // 发帖城市id，格式：省,市,区
  latitude: "", // 发帖纬度
  longitude: "", // 发帖经度
  deliveryMethod: 1, // 邮寄方式
  isDeliveryCovered: false, // 是否包邮
  isNeedHelp: false, // 是否求助
});
const { isType0, isExchangeType } = usePublishType(pushData);

const submitLoading = ref(false);

const clonePushData = uni.$uv.deepClone(pushData.value);

const rules = ref({
  articleType: {
    type: "number",
    required: true,
    message: "请选择种类",
    trigger: ["blur", "change"],
  },
  title: {
    type: "string",
    required: true,
    message: "请填写标题",
    min: 3,
    max: 30,
    trigger: ["blur", "change"],
  },
  content: {
    type: "string",
    required: false,
    message: "文字数量超出最大限制",
    max: 1000,
    trigger: ["blur", "change"],
  },
  images: {
    type: "string",
    required: true,
    message: "请上传图片",
    trigger: ["blur", "change"],
  },
  price: {
    type: "any",
    required: true,
    message: "请填写价格",
    trigger: ["blur", "change"],
  },
  location: {
    type: "string",
    message: "请选择发帖城市",
    trigger: ["blur", "change"],
  },
});

provide("rules", rules);

const uvFormRef = ref(null);

// 提交数据字段校验
const validateData = () => {
  return new Promise((resolve, reject) => {
    uvFormRef?.value
      ?.validate()
      .then((res) => {
        resolve(res);
      })
      .catch((errors) => {
        reject(errors);
      });
  });
};
// 重置表单,uv-form的不好用,所以自己写了一下
const resetData = () => {
  pushData.value = {
    ...uni.$uv.deepClone(clonePushData),
    articleType: pushData.value.articleType,
    location: pushData.value.location,
    locationId: pushData.value.locationId,
    latitude: pushData.value.latitude,
    longitude: pushData.value.longitude,
    images: pushData.value.images,
    title: pushData.value.title,
    content: pushData.value.content,
  };
  uvFormRef.value.clearValidate();
};

watch(pushData, (val, oldVal) => {
  console.log("pushData", pushData.value);
  // 变更发布类型，重置表单
  if (val.articleType !== oldVal.articleType) {
    resetData();
    hideBackAlert();
    return false;
  }
  // 因为没有表单元素无法触发change校验，所以要手动触发一下
  if (val.images !== oldVal.images) {
    uvFormRef.value.validateField("images");
  }
  if (!isBackAlert.value) {
    showBackAlert();
    isBackAlert.value = true;
  }
});

onLoad(() => {
  hideBackAlert();
});

const handlerPublish = () => {
  validateData()
    .then((res) => {
      console.log(res);

      submitLoading.value = true;

      const data = {
        ...pushData.value,
      };
      // data.images = data.images.split(',')

      articleManagement
        .createArticle(data)
        .then((res) => {
          console.log("res", res);
          const { code, data } = res;
          if (code === 0) {
            isBackAlert.value = false;
            hideBackAlert();
            uni.showToast({
              title: "发布成功",
              icon: "success",
              duration: 2000,
            });
            setTimeout(() => {
              uni.navigateBack({
                delta: -1,
              });
            }, 2000);
          }
        })
        .finally(() => {
          submitLoading.value = false;
        });
    })
    .catch((errors) => {
      console.log(errors);
      uni.showToast({
        icon: "error",
        title: "必填项未填写！",
      });
    });
};
</script>

<style lang="scss">
page {
  background: #f9f9f9;
}

.topSelect {
  background: #fff;
}

.pulishButton {
  width: 690rpx;
  margin: 0 auto;
}

.publishWrap {
  .uv-form-item__body {
    padding: 0 !important;
  }

  .uv-form-item__body__right__message {
    display: none;
  }
}
</style>
